let isConnect = false;

setTimeout(function () {
    $(document).ready(function () {
        // checkMobile();
        initWebSocket();
        setTransLed();

        window.addEventListener("load", function () {
        });

        window.addEventListener("unload", function () {
            console.log("stopWebSocket");
            stopWebSocket();
        });

        window.onresize = function () {
        };

        $("#logo").on('error',function () {
            $(this).hide();
        });

        // $("#index").on("click", ".main-box button", function () {
        $("#main-box button").click( function () {
            let key = this.id;
            let param = this.getAttribute("param");
            let color = param ? param : "white";
            let value = this.value === 0 || !this.value ? 1 : 0;
            this.value = value;
            this.classList.add(LedStatus[value] + "-" + color);
            // Send Json object to server
            let data = {};
            if (key === "stream-1") {
                // let stream1_server = document.getElementById("stream-1-server").value;
                // let stream1_key = document.getElementById("stream-1-key").value;
                // if (!stream1_server && !stream1_key) {
                //     return;
                // }
                // data["stream-1-server"] = stream1_server;
                // data["stream-1-key"] = stream1_key;
            } else if (key === "stream-2") {
                // let stream2_server = document.getElementById("stream-2-server").value;
                // let stream2_key = document.getElementById("stream-2-key").value;
                // if (!stream2_server && !stream2_key) {
                //     return;
                // }
                data["stream-1-server"] = $("#stream-1-server").val();
                data["stream-1-key"] = $("#stream-1-key").val();
                data["stream-2-server"] = $("#stream-2-server").val();
                data["stream-2-key"] = $("#stream-2-key").val();
                data["stream-3-server"] = $("#stream-3-server").val();
                data["stream-3-key"] = $("#stream-3-key").val();
            } else if (key === "sdcard-space") {
                data["record-path-first"] = 0;
            } else if (key === "udisk-space") {
                data["record-path-first"] = 1;
            } else if (key === "pull-stream-save") {
                let stream_list = [];
                $("input[id^='pull-stream-']").each(function () {
                    let value = $(this).val() ? $(this).val() : "null";
                    stream_list.push(value);
                });
                data["pull_stream"] = stream_list;
            } else if (key === "umd-save") {
                let umd_object = {};
                let umd_error = false;
                $("input[id^='umd_']").each(function () {
                    let regex = /^[a-zA-Z0-9]{1,6}$/;
                    if (!regex.test($(this).val())) {
                        umd_error = true;
                        return;
                    }
                    umd_object[$(this).attr("id")] = $(this).val();
                });
                if (umd_error) {
                    $("#umd-error-message").text("UMD name should be 1 to 6 characters and only contain letters and numbers.");
                    return;
                } else {
                    $("#umd-error-message").text("");
                }

                data["umd"] = umd_object;
            } else {
                data[key] = value;
            }

            sendMessage(JSON.stringify(data));
        });

        $("#index").on("input propertychange", "#putter", (e) => {
            let value = Number(e.currentTarget.value);
            let data = {};
            data["putter"] = value;
            setTransLed();
            sendMessage(JSON.stringify(data));
        });

    });
}, 200);


function handleResult(data) {
    console.log(data);
    if (!data) {
        console.log("data is empty");
        return;
    }
    isConnect = true;
    let element;
    const keys = Object.keys(data);
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        if (!key || data[key] == null) {
            console.log("key or value is empty");
        } else if (key === "record-path-first") {
            if (data[key] === 0) {
                $("#udisk-space").removeClass("active-white");
                $("#sdcard-space").addClass("active-white");
            } else {
                $("#sdcard-space").removeClass("active-white");
                $("#udisk-space").addClass("active-white");
            }
        } else if (key === "udisk-space") {
            $("#udisk-space").text(data[key]);
        } else if (key === "sdcard-space") {
            $("#sdcard-space").text(data[key]);
        } else if (key === "pull_stream") {
            for (let j = 0; j < data[key].length; j++) {
                $("#pull-stream-" + (j+1)).val(data[key][j]);
            }
        } else if (key === "umd") {
            $.each(data[key], function(key, value) {
                // console.log('Key: ' + key + ', Value: ' + value);
                $("#" + key).val(value);
            });
        } else {
            element = $("#" + key);
            if (!element || !element[0]) {
                continue;
            }
            if (element[0].nodeName === "BUTTON") {
                if (data[key] === 0) {
                    element.removeClass(
                        "active-green active-red active-white flash-green flash-red flash-white"
                    );
                } else {
                    let param = element[0].getAttribute("param");
                    let color = param ? param : "white";
                    element.addClass(LedStatus[data[key]] + "-" + color);
                }
                element.val(data[key]);
            } else if (element[0].nodeName === "INPUT") {
                element.val(data[key]);
            }
        }
    }
    //reloading the page to update the values
    // location.reload();
}

function setTransLed() {
    var ledstring = "";
    var transitions_slider_led = $("#transitions_slider_led");

    var target = $("input[name=main-transitions]")[0];
    if (!target) {
        return;
    }
    var value = Number(target.value);
    var percent = 0;
    percent = value / target.max;
    percent = percent.toFixed(1);
    percent = Number(percent);
    var num = 16 * percent;
    for (let i = 0; i < 16; i++) {
        if (i >= num) {
            ledstring +=
                '<div style="height: 15px; width: 6px; background-color: var(--item-bg); border-radius: 5px;"></div>';
        } else {
            ledstring +=
                '<div style="height: 15px; width: 6px; background: white; border-radius: 5px;"></div>';
        }
    }
    transitions_slider_led.html(ledstring);
}